package cmd

import (
	"os"

	"gitlab.bangdao-tech.com/ops/ck-migrator/pkg/logger"

	"gitlab.bangdao-tech.com/ops/ck-migrator/pkg/config"

	"github.com/spf13/cobra"
)

var configFile string

// RootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "ck-migrator",
	Short: "clickhouse migration tool",
	Long:  `ck-migrator is a clickhouse migration tool`,
	PersistentPreRun: func(cmd *cobra.Command, args []string) {
		logger.Init()
		if err := config.LoadConfig(configFile); err != nil {
			logger.Fatal(err.Stack())
		}
	},
	PersistentPostRun: func(cmd *cobra.Command, args []string) {
		logger.Close()
	},
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	err := rootCmd.Execute()
	if err != nil {
		os.Exit(1)
	}
}

func init() {
	rootCmd.AddCommand(genCmd, runCmd)
	rootCmd.PersistentFlags().StringVarP(&configFile, "config-file", "c", "config.yaml", "/path/to/config-file")
}
